import { Pages } from "../to/pages/Pages";
import { R } from "../to/pages/R";
import { router } from "../to/pages/routerVisitor";
import { toLiveDetail } from "../to/toLiveDetail";
import { toRedPacket } from "../to/toRedPacket";
import { addMaxFail, setMaxFail } from "./maxFail";


export function joinAndWaitOpen(userId: string) {
    let liveRoomCtx = toLiveDetail()
    let activities: any[] = liveRoomCtx.get<any[]>('activities') || []
    if (activities.length === 0) {
        addMaxFail()
        return false;
    }
    if (!liveRoomCtx.isPage(Pages.live)) {
        addMaxFail()
        return false;
    }

    if (userId) {
        if (activities && activities.length > 0) {
            let roomRedPacketInfo = activities.find(it => it.openRedPacket)
            const startDate = Date.now()
            while (!roomRedPacketInfo && Date.now() - startDate < 1000 * 5) {
                liveRoomCtx = router.getCurrentContext()
                activities = liveRoomCtx.get<any[]>('activities') || []
                roomRedPacketInfo = activities.find(it => it.openRedPacket)
                sleep(1000)
            }

            if (!roomRedPacketInfo) {
                addMaxFail()
                return false;
            }

            setMaxFail(0)
            roomRedPacketInfo.openRedPacket()

            sleep(2000)
            const redLoading = selector().idEndsWith(R.action_view).findOnce()
            if (!redLoading) {
                events.emit('log', `红包加载超时`)
                addMaxFail()
                return false;
            }

            const redPacketCtx = toRedPacket()
            if (!redPacketCtx.isPage(Pages.redPacket)) {
                addMaxFail()
                return false;
            }
            // 参加红包
            console.log(redPacketCtx.all())
        }
    }
}